<?php
class db_relation
{
	/*
	*	Adds a Positive or Negative Relation, or deletes the relation. 
	*	
	*/
	public function changeRelation($currentuser, $relateduser, $action)
	{
		// Add a Positive Relation
		if("add" == $action)
		{
			db_relation::addFollow($currentuser, $relateduser);
		}
		
		// Add a Negative Relation
		elseif("block" == $action)
		{
			db_relation::addBlock($currentuser, $relateduser);
		}
		
		// Delete the current relation
		elseif("remove" == $action)
		{
			db_relation::deleteRelation($currentuser, $relateduser);
		}
	}
	/*
	*	Adds a Positive Relation
	*
	*	Params: id1 = Current User, id2 = Related User
	*/
	private function addFollow($id1, $id2)
	{
		$sql = "SELECT * FROM follow WHERE User_ID=%d AND Follow_ID=%d";
		$query = sprintf($sql,
            mysql_real_escape_string($id1),
			mysql_real_escape_string($id2));
		$result = $this->mySql->makeQuery($query);	
		if(0 == mysql_num_rows($result))
		{
			$sql = "INSERT INTO follow (User_ID, Follow_ID, Action) VALUES (%d,%d, 1)";
			$query = sprintf($sql,
				mysql_real_escape_string($id1),
				mysql_real_escape_string($id2));
			$this->mySql->makeQuery($query);
		}
		else
		{
			$sql = "UPDATE follow SET User_ID = %d, Follow_ID = %d, Action = 1 WHERE User_ID = %d AND Follow_ID = %d";
			$query = sprintf($sql,
				mysql_real_escape_string($id1),
				mysql_real_escape_string($id2),
				mysql_real_escape_string($id1),
				mysql_real_escape_string($id2));
			$this->mySql->makeQuery($query);
		}
	}
	/*
	*	Adds a Negative Relation
	*
	*	Params: id1 = Current User, id2 = Related User
	*/
	private function addBlock($id1, $id2)
	{
		$sql = "SELECT * FROM follow WHERE User_ID=%d AND Follow_ID=%d";
		$query = sprintf($sql,
            mysql_real_escape_string($id1),
			mysql_real_escape_string($id2));
		$result = $this->mySql->makeQuery($query);	
		if(0 == mysql_num_rows($result))
		{
			$sql = "INSERT INTO follow (User_ID, Follow_ID, Action) VALUES (%d,%d, -1)";
			$query = sprintf($sql,
				mysql_real_escape_string($id1),
				mysql_real_escape_string($id2));
			$this->mySql->makeQuery($query);
		}
		else
		{
			$sql = "UPDATE follow SET User_ID = %d, Follow_ID = %d, Action = -1 WHERE User_ID = %d AND Follow_ID = %d";
			$query = sprintf($sql,
				mysql_real_escape_string($id1),
				mysql_real_escape_string($id2),
				mysql_real_escape_string($id1),
				mysql_real_escape_string($id2));
			$this->mySql->makeQuery($query);
		}
	}
	/*
	*	Deletes a Relation
	*
	*	Params: id1 = Current User, id2 = Related User
	*/
	private function deleteRelation($id1, $id2)
	{
		$sql = "DELETE FROM follow WHERE User_ID=%d AND Follow_ID=%d";
		$query = sprintf($sql,
            mysql_real_escape_string($id1),
			mysql_real_escape_string($id2));
		$this->mySql->makeQuery($query);	
	}
}
?>